#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>

#include "graph.h"


// struct Node {
// 	ELementType ele;
// 	float weight;
// 	struct Node* next;
// };
PtrToNode createNode(ELementType x, float weight) {
	PtrToNode node = malloc(sizeof(struct Node));
	if (node == NULL) perror("out of space");
	node->ele = x;
	node->weight = weight;
	node->next = NULL;
	return node;
}

// struct Graph {
// 	int capacity;
// 	int size;
// 	struct Node* nodeList;
// };
PtrToGraph initGraph(int capacity) {
	PtrToGraph graph = malloc(sizeof(struct Graph));
	graph->capacity = capacity;
	graph->size = 0;
	graph->nodeList = malloc(sizeof(PtrToNode) * capacity);
	return graph;
}

PtrToNode find(PtrToGraph graph, ELementType x) {
	PtrToNode target;
	int i = 0;
	for (i = 0; i < graph->capacity; i++) {
		PtrToNode node = graph->nodeList[i];
		if (node != NULL && node->ele == x) {
			target = node;
			break;
		}
	}
	return target;
}

void addNode(PtrToGraph graph, ELementType x) {
	if (graph->size == graph->capacity) {
		printf("graph full");
		return;
	}
	if (find(graph, x) != NULL) {
		printf("element %0.1f exists\n", x);
		return;
	}

	int i = 0;
	PtrToNode node;
	for (i = 0; i < graph->capacity; i++) {
		node = graph->nodeList[i];
		if (node == NULL)break;
	}
	graph->nodeList[i] = createNode(x, 0.0f);
	graph->size ++;
}

void printAllNode(PtrToGraph graph) {
	PtrToNode node;
	int count = 0;
	int i = 0;
	for (i = 0; i < graph->capacity && count < graph->size; i++) {
		node = graph->nodeList[i];
		if (node != NULL) {
			count ++;
			// printf("%.1f\n", node->ele);
			printAdjacent(node);
		} else {
			// printf("i=%d is NULL\n", i);
		}
	}
}

void printAdjacent(PtrToNode node) {
	while (node != NULL) {
		printf("ele=%.1f,weight=%.1f  ", node->ele, node->weight);
		node = node->next;
	}
	printf("\n");
}

void addEdge(PtrToGraph graph, ELementType x, ELementType y, float weight) {
	// find the x node
	PtrToNode nodeX = find(graph, x);
	if (nodeX == NULL) {
		printf("element %.1f not found", x);
		return;
	}
	PtrToNode preNode = nodeX;
	PtrToNode nextNode = nodeX->next;
	while (nextNode != NULL) {
		if (nextNode->ele == y) {
			printf("(%.1f %.1f) already adjacent", x, y);
			return;
		}
		preNode = nextNode;
		nextNode = nextNode->next;
	}
	preNode->next = createNode(y, weight);
}